package com.usooft.metaTalent.core.base.file;

import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.usooft.framework.core.utils.FunctionUtils.index;

@Component
public class FileManager {

    private final Map<String, FileProvider> fileProviderMap;

    public FileManager(List<FileProvider> fileProviders) {
        fileProviderMap = index(fileProviders, FileProvider::getPrefix);
    }

    private FileProvider getFileProvider(String prefix) {
        FileProvider fileProvider = fileProviderMap.get(prefix);
        if (fileProvider == null) {
            throw new UnsupportedOperationException("不支持的路径前缀：" + prefix);
        }
        return fileProvider;
    }

    private PathSpec resolve(String path) {
        String[] parts = path.split(":");
        if (parts.length < 2) {
            throw new IllegalArgumentException("路径不符合 prefix:path 格式");
        }
        return new PathSpec(parts[0], parts[1]);
    }

    public String store(InputStream is,
                        String path,
                        String extension) throws IOException {
        PathSpec pathSpec = resolve(path);
        String date = DateFormatUtils.format(new Date(), "yyyyMMdd");
        String target = Path.of(pathSpec.path(), date, NanoIdUtils.randomNanoId() + "." + extension).toString();
        getFileProvider(pathSpec.prefix()).store(target, is);
        return pathSpec.prefix() + ":" + target;
    }

    public File loadFile(String path) {
        PathSpec pathSpec = resolve(path);
        FileProvider fileProvider = getFileProvider(pathSpec.prefix());

        return fileProvider.load(pathSpec.path());
    }

    private record PathSpec(String prefix, String path) {

    }
}
